import { userStore } from "@/store/index";
import router from "@/router/index";
import { registerMicroApps } from "qiankun";
import pager from "@/utils/rxjs";

pager.subscribe(v => {                     // 在主应用注册呼机监听器，这里可以监听到其他应用的广播
  console.log(`[qiankun-base] 监听到子应用${v.from}发来消息：`, v)
  // store.dispatch('app/setToken', v.token)  // 这里处理主应用监听到改变后的逻辑
})

router.beforeEach(async (to, from, next) => {
  const userstore = userStore();
  if (!userstore.isLoggedIn) {
    await userstore.registerUser();
    await userstore.registryMenu();
    // 拿到菜单， 注册应用
    const apps = getMicorApps(userstore.menuList, userstore);
    registerMicroApps(apps);
  }

  /* 解决子应用内操作路由切换后， 再回来基座应用切换路由会导致history.state.back 错乱， 导致undefined */
  if (
    window.history.state === null ||
    window.history.state.back !== from.path
  ) {
    history.replaceState(
      {
        back: from.path,
        current: to.path,
        forward: null,
        position: NaN,
        replaced: false,
        scroll: null,
      },
      to.path
    );
  }
  next();
});

function getMicorApps(menuList, userstore, loader) {
  const microApps = [];

  function loader(load) {
    userstore.$patch((state) => {
      state.load = load;
    });
  }

  menuList.forEach((item) => {
    microApps.push({
      name: item.url.split("/")[1],
      entry: item.path,
      container: "#sub-app",
      activeRule: item.url,
      loader,
      props: {
        routerData: item.children,
        commonStore: userstore,
        pager,
      },
    });
  });
  return microApps;
}
